package com.zoroki.hmusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zoroki.hmusic.constant.MessageConstant;
import com.zoroki.hmusic.entity.Favorite;
import com.zoroki.hmusic.entity.Playlist;
import com.zoroki.hmusic.entity.Song;
import com.zoroki.hmusic.entity.User;
import com.zoroki.hmusic.es.EsUserRepository;
import com.zoroki.hmusic.mapper.FavoriteMapper;
import com.zoroki.hmusic.mapper.PlaylistMapper;
import com.zoroki.hmusic.mapper.SongMapper;
import com.zoroki.hmusic.mapper.UserMapper;
import com.zoroki.hmusic.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoroki.hmusic.util.BCryptUtil;
import com.zoroki.hmusic.util.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zoroki
 * @since 2023-05-10
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    ISongService songService;

    @Autowired
    SongMapper songMapper;

    @Autowired
    PlaylistMapper playlistMapper;

    @Autowired
    IFavoriteService favoriteService;

    @Autowired
    IFavoriteSongService favoriteSongService;

    @Autowired
    IFavoritePlaylistService favoritePlaylistService;

    @Autowired
    IPlaylistService playlistService;
    @Autowired
    IPlaylistSongService playlistSongService;


    @Autowired
    EsUserRepository esUserRepository;

    @Override
    public User findUserByColumn(String columnName, Object odd) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
//        wrapper.select(
//                "id",
//                "username",
//                "gender",
//                "email",
//                "phone",
//                "remark",
//                "avatar",
//                "created_at",
//                "updated_at"
//        );
        wrapper.eq(columnName, odd);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public int addUser(User user) {
        //添加用户需要对密码进行加密
        String encode = BCryptUtil.encode(user.getPassword());
        user.setPassword(encode);
        int insert = userMapper.insert(user);

        int flag = 0;
        if (insert > 0) {
            //如果是用户添加成功
            //添加favorite数据
            int i = favoriteService.addFavorite(user.getId());
            if (i > 0) {
                flag = 1;
                //并且添加 到 es
                User newUser = userMapper.selectById(user.getId());
                try{
                    esUserRepository.save(newUser);
                }catch (Exception e){
                    log.error("esUser添加成功:{}",e.getMessage());
                    return flag;
                }
            }
        }
        return flag;
    }

    @Override
    public int updateUser(User user) {
        if (user.getPassword() != null) {
            //更新用户需要对密码进行加密
            String encode = BCryptUtil.encode(user.getPassword());
            user.setPassword(encode);
        }

//        if (user.getAvatar() != null) {
//            //删除原来的头像
//            User oldUser = userMapper.selectById(user.getId());
//            String avatar = oldUser.getAvatar();
//            String fileName = avatar.substring(avatar.lastIndexOf("/") + 1);
//            QiniuUtil.deleteFile(MessageConstant.FOLDER_IMG + fileName);
//        }

        int update = userMapper.updateById(user);

        int flag = 0;
        if (update > 0) {
            //如果是用户更新成功
            //添加到es
            flag = 1;
            esUserRepository.save(user);
        }
        return flag;
    }

    @Override
    public List<User> findUserBySearStr(String searchStr) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.like("username", searchStr)
                .or()
                .like("remark", searchStr)
                .or()
                .like("email", searchStr)
                .or()
                .like("phone", searchStr);

        return userMapper.selectList(wrapper);
    }

    @Override
    public SearchHits<User> findUserByKeyword(String keyword) {
        return esUserRepository.findUserByUsernameOrRemark(keyword, keyword);
    }

    @Override
    public Page<User> getUserPageByKeyword(String keyword, int pageIndex) {
        return esUserRepository.findUsersByUsernameOrRemark(keyword, keyword, PageRequest.of(pageIndex, 6, Sort.by(Sort.Order.asc("createdAt"))));
    }

    @Override
    public int deleteUserById(int id) {
        //1.根据id查询用户
        User user = userMapper.selectById(id);
        if (user == null) {
            return -1;
        }

        //2.删除七牛云中的头像数据
        String avatar = user.getAvatar();
        if (avatar != null) {
            String fileName = avatar.substring(avatar.lastIndexOf("/") + 1);
            QiniuUtil.deleteFile(fileName);
        }

        //3.删除我所创建的song
        QueryWrapper<Song> songQueryWrapper = new QueryWrapper<Song>();
        songQueryWrapper.eq("user_id", id);
        List<Song> songs = songMapper.selectList(songQueryWrapper);

        for (Song song : songs) {
            songService.deleteSong(song.getId());
        }

        //5.删除我所创建的playlist
        QueryWrapper<Playlist> playlistQueryWrapper = new QueryWrapper<Playlist>();
        playlistQueryWrapper.eq("user_id", id);
        List<Playlist> playlists = playlistMapper.selectList(playlistQueryWrapper);
        for (Playlist playlist : playlists) {
            playlistService.deletePlaylistById(playlist.getId());
        }

        //6.删除favorite
        favoriteService.deleteFavorite(id);

        //7.从es中删除user信息
        esUserRepository.deleteById(String.valueOf(id));

        //8.删除用户信息
        return userMapper.deleteById(id);
    }

    @Override
    public User findUserById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public User findUserByPlaylistId(int playlistId) {
        Playlist playlist = playlistService.findPlaylistById(playlistId);
        return findUserById(playlist.getUserId());
    }

    @Override
    public int editPasswordByEmail(String email, String password) {
        User userByEmail = getUserByEmail(email);
        String encode = BCryptUtil.encode(password);
        userByEmail.setPassword(encode);

        return userMapper.updateById(userByEmail);
    }

    @Override
    public User getUserByEmail(String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);

        return userMapper.selectOne(queryWrapper);
    }
}
